/* D:TalkTalk/piecesofuk version */
/*
 to compress...
 d:
 cd TalkTalk\piecesofuk\Javascript
 java -jar D:\Programming\Javascript\yuicompressor-2.3.5\build\yuicompressor-2.3.5.jar youTubePlayer.js -o youTubePlayer.min.js
*/
googleTranslateInit = function() {

}

google.load("language", "1");
google.setOnLoadCallback(googleTranslateInit);


$(document).ready( function() {

  $("#playPauseVideo").unbind("click");
  $("#playPauseVideo").click( function() {
    playVideo();
  });

  $("#skipVideo").click( function() {
    ytplayer.seekTo(current + 10, true);
  });

  $("#theVolume").change( function() {
    var oldVolume = ytplayer.getVolume();
    var newVolume = $("#theVolume").attr("value");
    if (newVolume < 0 || newVolume > 100) {
      newVolume = oldVolume;
      $("#theVolume").attr("value", newVolume);
    }
    ytplayer.setVolume(newVolume);
  });

});

playVideo = function() {
    $("#playPauseVideo").removeClass("playVideo").addClass("pauseVideo");
    ytplayer.playVideo();
    $("#playPauseVideo").unbind("click");
    $("#playPauseVideo").click( function() {
      pauseVideo();
    });

}

pauseVideo = function() {
  $("#playPauseVideo").removeClass("pauseVideo").addClass("playVideo");
  ytplayer.pauseVideo();
  $("#playPauseVideo").unbind("click");
  $("#playPauseVideo").click( function() {
    playVideo();
  });

}
//window.loadFirebugConsole() ;
var duration = 0;
var durationSeconds = 0;
var durationMinutes = 0;
var intervalId = null;
var current = 0;
var ytplayer;
var dev_key = "AI39si5ZGB1rIF7dhn6_iSVb4cODOTLb1mNXMZh4w9SkHBfRvgquafK9yvbRIchpmQLMb37fQBU4EZMm1SkjvysIKKDcNtIPcw"
//var dev_key = "AI39si5ouGz0PefFfaai9d8hT8DqnXdHmzhmD92a_QktbJK4VnIpLbHDVAtvHw5bwWYDYrrHUonMozLZLG_VGyVsoQBC5sRdSA"
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://gdata.youtube.com/apiplayer?key=" + dev_key + "&enablejsapi=1&playerapiid=ytplayer",
//                       "ytapiplayer", "425", "356", "8", null, null, params, atts);
                       "ytapiplayer", "320", "240", "8", null, null, params, atts);
//    ytplayer.loadVideoById('6yy8Bqaytio', 0)

function XXXonYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
/*
          setInterval(updateytplayerInfo, 250);
          updateytplayerInfo();
          ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
*/
 //   ytplayer.cueVideoById('6yy8Bqaytio', 0) // love is a garden
//    ytplayer.cueVideoById('s_8VEnr5rds', 0) // stronger woman (valory)
//    ytplayer.cueVideoById('xq-ZmAYLeB8', 0) // Brandi Carlile-The Story
 //   ytplayer.cueVideoById('FE_D1grlleU', 0) // example of a not found video
    ytplayer.cueVideoById('z42jA3OOECc', 0) // i do (valory)

    ytplayer.addEventListener('onStateChange', 'ytplayerStateChange');
    ytplayer.addEventListener('onError', 'ytplayerError');
    intervalId = setInterval(updateStatus, 1000);
    $("#theVolume").attr("value", ytplayer.getVolume());
    updateStatus();
}

  var skipHeight = $("#skipPoints").height();


ytplayerStateChange = function(newState) {
  if (newState == -1) $("#status").text("unstarted");
  if (newState == 0) $("#status").text("ended");
  if (newState == 1) {
//    if ( $("#videoController").children().eq(0).attr("id") == "playVideo") {
    if ( $(".playVideo").length) {
      $("#playPauseVideo").removeClass("playVideo").addClass("pauseVideo");
      $("#playPauseVideo").unbind("click");
      $("#playPauseVideo").click( function() {
        pauseVideo();
      });
    }
    $("#status").text("playing");
    duration = ytplayer.getDuration();
    duration = Math.floor(duration)
    durationSeconds = duration % 60;
    durationMinutes = Math.floor(duration / 60);

    for (var i = 0; i < verses.length; i++) {
      var $theSpan = $("<span></span>").addClass("skipPoint").text(verses[i].Type)
                            .css("top", Math.floor(verses[i].Start/duration * skipHeight) + "px");
      var $timeSpan = $("<span></span>").addClass("skipTime").text(verses[i].Start);
      $theSpan.append($timeSpan);
//  console.log(verses[i].Start + " " + duration + " " + Math.floor(verses[i].Start/duration * 356) );
      $("#skipPoints").append($theSpan);
    }


    $(".skipPoint").click( function() {
      var seekTo = parseInt($(this).find(".skipTime").text(),10);
      ytplayer.seekTo(seekTo, true);
      for (var i = 0; i < lyrics.length; i++) {
        if (lyrics[i].Start >= seekTo) {
          $("#videoLyrics").html("");
          $("#translatedLyrics").html("");
          lyricPointer = i;
          nextLyricTime = lyrics[lyricPointer].Start;
          break;
        }
      }
      for (var i = 0; i < videoInfo.length; i++) {
        if (videoInfo[i].Start >= seekTo) {
          $("#videoInfoLeft").html("");
          videoInfoPointer = i;
          nextVideoInfoTime = videoInfo[videoInfoPointer].Start;
          break;
        }
      }
    });


  }
  if (newState == 2) $("#status").text("paused");
  if (newState == 3) $("#status").text("buffering");
  if (newState == 5) {
    $("#status").text("video cued");
  }
}

ytplayerError = function(errorCode) {
  if (errorCode == 100) alert("video not found or has been removed");
}

updateStatus = function() {
  current = ytplayer.getCurrentTime();
  $("#time").text(Math.floor(current / 60) + ":" + Math.floor(current) % 60 + "/" + durationMinutes + ":" + durationSeconds);
  if (ytplayer.getVideoBytesTotal() > 0) {
    var pcLoaded = Math.floor( ytplayer.getVideoBytesLoaded()/ytplayer.getVideoBytesTotal() * skipHeight);
//    console.log("loaded=" + ytplayer.getVideoBytesLoaded() + " Total=" + ytplayer.getVideoBytesTotal());
    $("#loaded").css("height", pcLoaded + "px");
  }
  if (duration > 0) {
    var played = Math.floor ( current/duration * skipHeight);
    $("#played").css("height", played + "px");
  }

  if (current > nextLyricTime) {
    $("#videoLyrics").html(lyrics[lyricPointer].Line);
/* temp remove
    google.language.translate(lyrics[lyricPointer].Line, "en",
          $("#langChoice").find("option:selected").attr("value"), function(result) {
      if (!result.error) {
        $("#translatedLyrics").html(result.translation)
      }
    });
*/
    if ( $("#jq-translate-ui").val() != "English") {

      google.language.translate(lyrics[lyricPointer].Line, "en",
          google.language.Languages[$("#jq-translate-ui").val().toUpperCase()], function(result) {
        if (!result.error) {
          $("#translatedLyrics").html(result.translation)
        }
      });
    }
    ++lyricPointer;
    nextLyricTime = lyrics[lyricPointer].Start;
  }

  if (current > nextVideoInfoTime) {
    $("#videoInfoLeft").html(videoInfo[videoInfoPointer].Html);
    ++videoInfoPointer;
    nextVideoInfoTime = videoInfo[videoInfoPointer].Start;
  }
}


var videoInfo = [];

videoInfoItem = function(start, html) {
  this.Start = start;
  this.Html = html;
}

videoInfo[0] = new videoInfoItem(1, "<p style='padding: 20px; font-size: 18px; text-align: center;'>" +
                  "I wrote this song not to be a guy-bashing song at all. " +
                  "This, to me, is just about women saying, 'There's more to me than I give my " +
                  "own self credit for, and if I want a certain kind of life, and I want a certain" +
                  " kind of happiness, it's up to me to get it.'</p><br>" +
                  "<p style='text-align:right; font-size: 10px;'>Jewel from GAC Nights: Live From Nashville</p>");
videoInfo[1] = new videoInfoItem(10, "<p style='padding: 20px; font-size: 18px; text-align: center;'>" +
                  "For women, it's hard sometimes, because I think men are " +
                  "raised to feel like they know they're gonna be on their own and they know " +
                  "they're gonna make a living in the world and it's their way and they've gotta " +
                  "find it.</p><br>" +
                  "<p style='text-align:right; font-size: 10px;'>Jewel from GAC Nights: Live From Nashville</p>");
videoInfo[2] = new videoInfoItem(18, "<div style='text-align: center;'></div>");
videoInfo[3] = new videoInfoItem(212, "<div style='text-align: center; padding: 20px;'>Jewel, Stronger Woman. Video directed by Trey Fanjoy, " +
                  "Produced by Rebecca Scarpatti. &copy; 2008 The Valory Music Co</div>");

/*
videoInfo[2] = new videoInfoItem(18, "<div style='text-align: center;'><img src='Videos/StrongerWoman/poltz.png'></div>");
videoInfo[3] = new videoInfoItem(29, "<div style='text-align: center;'><img src='Videos/StrongerWoman/notWelcome.png'></div>");
videoInfo[4] = new videoInfoItem(212, "<div style='text-align: center; padding: 20px;'>Jewel, Stronger Woman. Video directed by Trey Fanjoy, " +
                  "Produced by Rebecca Scarpatti. &copy; 2008 The Valory Music Co</div>");
*/

/*

 http://www.gactv.com/gac/nw_headlines/article/0,3034,GAC_26063_5829299_,00.html
 "I wrote this song not to be a guy-bashing song at all," she told the national radio show GAC Nights:
 Live From Nashville.
 "This, to me, is just about women saying, 'There's more to me than I give my own self credit
 for, and if I want a certain kind of life, and I want a certain kind of happiness, it's up
 to me to get it.' For women, it's hard sometimes, because I think men are raised to feel like
 they know they're gonna be on their own and they know they're gonna make a living in the world
 and it's their way and they've gotta find it."

Women, she says, often have conflicting voices that suggest maybe a man will take care of them. In many cases, females frequently discover as they age that they never quite fulfilled their dreams, and she suggests that leads to a lot of bitterness.

"I've seen it happen a million times," she said. "So I wanted to write it to remind myself and everybody and any father that has a daughter, to raise a woman to be a strong woman. And men should like it, 'cause we're less naggy that way anyway!"

*/

videoInfo[videoInfo.length] = new videoInfoItem(9999, "");

var nextVideoInfoTime = videoInfo[0].Start;
var videoInfoPointer = 0;


var verses = [];

verse = function(start, type) {
  this.Start = start;
  this.Type = type;
}

verses[0] = new verse(0, "Intro");
verses[1] = new verse(30, "Verse1");
verses[2] = new verse(60, "Chorus");
verses[3] = new verse(93, "Verse2");
verses[4] = new verse(123, "Chorus");
verses[5] = new verse(149, "Bridge");
verses[6] = new verse(180, "Chorus");

var lyrics = [];

lyricLine = function(start, line) {
  this.Start = start;
  this.Line = line;
}

lyrics[0] = new lyricLine(31, "We've been doing this war dance together");
lyrics[1] = new lyricLine(34, "For some time I know");
lyrics[2] = new lyricLine(40, "Treating love like a battlefield");
lyrics[3] = new lyricLine(43, "And taking it slow");
lyrics[4] = new lyricLine(49, "Will you blink?");
lyrics[5] = new lyricLine(50, "What do you think?");
lyrics[6] = new lyricLine(53, "The union we propose");
lyrics[7] = new lyricLine(56, "Is dangerous I know");
lyrics[8] = new lyricLine(61, "Because love is a game until it's played");
lyrics[9] = new lyricLine(65, "And if it's lost it can't ever be saved");
lyrics[10] = new lyricLine(68, "We have Heaven to gain and Hell to lose");
lyrics[11] = new lyricLine(73, "And the difference is up to me and you");
lyrics[12] = new lyricLine(77, "So if you will, I will stop saying I won't");
lyrics[13] = new lyricLine(83, "And start saying I do");
lyrics[14] = new lyricLine(89, "I do");
lyrics[15] = new lyricLine(94, "Life can take a long time");
lyrics[16] = new lyricLine(97, "If you make the wrong choice");
lyrics[17] = new lyricLine(102, "But time sure seems to fly by");
lyrics[18] = new lyricLine(105, "When I hear your voice");
lyrics[19] = new lyricLine(111, "The stakes are high");
lyrics[20] = new lyricLine(113, "How will we find the courage to believe");
lyrics[21] = new lyricLine(118, "We will succeed?");
lyrics[22] = new lyricLine(123, "Because love is a game until it's played");
lyrics[23] = new lyricLine(127, "And if it's lost it can't ever be saved");
lyrics[24] = new lyricLine(131, "We have Heaven to gain and Hell to lose");
lyrics[25] = new lyricLine(135, "And the difference is up to me and you");
lyrics[26] = new lyricLine(139, "So if you will, I will stop saying I won't");
lyrics[27] = new lyricLine(145, "And start saying I do");
lyrics[28] = new lyricLine(149, "Well, our hearts are locked inside an iron box");
lyrics[29] = new lyricLine(157, "We're both too afraid to reveal our most tender parts");
lyrics[30] = new lyricLine(181, "Because love is a game until it's played");
lyrics[31] = new lyricLine(185, "And if it's lost it can't ever be saved");
lyrics[32] = new lyricLine(189, "We have Heaven to win and Hell to lose");
lyrics[33] = new lyricLine(193, "And the difference is up to me and you");
lyrics[34] = new lyricLine(197, "So if you will, I will stop saying I won't");
lyrics[35] = new lyricLine(202, "Stop saying I can't");
lyrics[36] = new lyricLine(205, "Is that what you said?");
lyrics[37] = new lyricLine(207, "Because if you did, I do.");
lyrics[38] = new lyricLine(213, "I do");
lyrics[39] = new lyricLine(216, "If you want me to");
lyrics[40] = new lyricLine(222, "I do");
lyrics[41] = new lyricLine(226, "If you want me to");
lyrics[lyrics.length] = new lyricLine(9999, "");

var nextLyricTime = lyrics[0].Start;
var lyricPointer = 0;
